var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var speed = null, p1 = null, angle = null, radians = null, xunits = null, yunits = null, ball = null;
var balls = null;
function Point(x, y){
    this.x = x;
    this.y = y;
}

function Ball(x, y, angle, speed, radius){
    this.speed = speed;
    this.radius = radius;
    this.p = new Point(x, y);
    this.angle = angle;
}

function draw(){
    context.fillStyle = '#cccccc';
    context.fillRect(0, 0, 500, 500);
    context.strokeRect(0, 0, 500, 500);
    for (var i = 0, len = balls.length; i < len; i++) {
        uploadBall(balls[i]);
        context.beginPath();
        context.fillStyle = 'green';
        context.arc(balls[i].p.x, balls[i].p.y, balls[i].radius, 0, 2 * Math.PI);
        context.fill();
        context.closePath();
    }
}

/**
 * 更新球的状态，当球碰壁的时候就反弹，并前进。
 * @param ball
 */
function uploadBall(ball){
    radians = ball.angle * Math.PI / 180;
    xunits = ball.speed * Math.cos(radians);
    yunits = ball.speed * Math.sin(radians);

    ball.p.x += xunits;
    ball.p.y += yunits;
    if (ball.p.x > canvas.width || ball.p.x < 0) {
        ball.angle = 180 - ball.angle;
    } else if (ball.p.y > canvas.height || ball.p.y < 0) {
        ball.angle = 360 - ball.angle;
    }
}

(function(){
    speed = 1;
    p1 = new Point(100, 100);
    ball = new Point(100, 100);
    angle = 30;

    // 创建两个球
    balls = [];

    // 不同的速度，不同的半径
    var numBalls = 20;
    var maxSize = 20;
    var minSize = 3;
    var maxSpeed = 20;
    var minSpeed = 1;

    var tempball = null;
    for (var i = 0; i < numBalls; i ++) {
        var tempAngle =  Math.floor(Math.random() * 360);
        var tempSpeed = Math.floor(Math.random() * (maxSpeed - minSpeed) + minSpeed);
        var tempRadius = Math.floor(Math.random() * (maxSize - minSize) + minSpeed);
        var x = Math.floor(Math.random() * 450 + 30);
        var y = Math.floor(Math.random() * 450 + 30);
        tempball = new Ball(x, y, tempAngle,tempSpeed, tempRadius);
        balls.push(tempball);
    }

    window.setInterval("draw()", 30);
    // draw();
})();